package com.yuanchu.store.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanchu.store.dao.YoshopRegionDao;
import com.yuanchu.store.entity.YoshopRegionEntity;
import com.yuanchu.store.service.YoshopRegionService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service("yoshopRegionService")
public class YoshopRegionServiceImpl extends ServiceImpl<YoshopRegionDao, YoshopRegionEntity> implements YoshopRegionService {

    @Override
    public Map<Integer, YoshopRegionEntity> queryRegionTreeAddress() {
        List<YoshopRegionEntity> list = this.list();
        Map<Integer, YoshopRegionEntity> rootTree = new HashMap<>();

        for (YoshopRegionEntity item : list) {
            if (item.getPid() == 0) { // 根节点
                rootTree.put(item.getId(), buildRegionTree(list, item));
            }

        }
        return rootTree;
    }


    private YoshopRegionEntity buildRegionTree(List<YoshopRegionEntity> allRegions, YoshopRegionEntity parent) {

        Map<Integer, YoshopRegionEntity> cityMap = new HashMap<>();
        Map<Integer, YoshopRegionEntity> regionMap = new HashMap<>();
        parent.setCity(cityMap);
        parent.setRegion(regionMap);

        for (YoshopRegionEntity region : allRegions) {
            if (Objects.equals(region.getPid(), parent.getId())) {
                if (region.getLevel() == 2) { // 假设level为2表示城市
                    cityMap.put(region.getId(), buildRegionTree(allRegions, region));
                } else {
                    regionMap.put(region.getId(), buildRegionTree(allRegions, region));
                }
            }
        }

        return parent;
    }





    public Map<Integer, YoshopRegionEntity> queryRegionTreeAddress2() {
        List<YoshopRegionEntity> list = this.list();
        Map<Integer, YoshopRegionEntity> rootTree = new HashMap<>();

        for (YoshopRegionEntity item : list) {
            if (item.getPid() == 0) { // 根节点
                rootTree.put(item.getId(), buildRegionTree2(list, item));
            }

        }
        return rootTree;
    }
    private YoshopRegionEntity buildRegionTree2(List<YoshopRegionEntity> allRegions, YoshopRegionEntity parent) {
        Map<Integer, YoshopRegionEntity> childrenMap = new HashMap<>();
        parent.setChildren(childrenMap);

        for (YoshopRegionEntity region : allRegions) {
            if (Objects.equals(region.getPid(), parent.getId())) {
                childrenMap.put(region.getId(), buildRegionTree(allRegions, region));
            }
        }

        return parent;
    }



}